package com.wjc.server.service;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjc.server.dto.LoginUserDto;
import com.wjc.server.dto.PageDto;
import com.wjc.server.dto.ResourceDto;
import com.wjc.server.dto.UserDto;
import com.wjc.server.entity.User;
import com.wjc.server.entity.UserExample;
import com.wjc.server.exception.BusinessException;
import com.wjc.server.exception.BusinessExceptionCode;
import com.wjc.server.mapper.MyUserMapper;
import com.wjc.server.mapper.UserMapper;
import com.wjc.server.util.CopyUtil;
import com.wjc.server.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;


@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private MyUserMapper myUserMapper;

    private static final Logger LOG= LoggerFactory.getLogger(UserService.class);

    //查询
    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        UserExample userExample = new UserExample();
        List<User> userList= userMapper.selectByExample(userExample);
        PageInfo<User> pageInfo=new PageInfo<>(userList);
        pageDto.setTotal(pageInfo.getTotal());

        List<UserDto> userDtosList = CopyUtil.copyList(userList,UserDto.class);
        pageDto.setList(userDtosList);

    }

    //保存
    public void save(UserDto userDto){

        User user=CopyUtil.copy(userDto,User.class);
        if (ObjectUtils.isEmpty(user.getId())){
            //新增
            user.setId(snowFlake.nextId());
            User userDb = selectByLoginName(userDto.getLoginName());
            if(!ObjectUtils.isEmpty(userDb)){
                //若数据库存在此用户名则抛出异常
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }else {
                userMapper.insert(user);
            }

        }else {
            userMapper.updateByPrimaryKeySelective(user);
        }

    }

    //修改密码
    public void savePassword(UserDto userDto){
        User user = CopyUtil.copy(userDto, User.class);
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void delete(Long id){
        userMapper.deleteByPrimaryKey(id);
    }

    //根据登录名查询用户信息
    public User selectByLoginName(String loginName){
        UserExample userExample=new UserExample();
        userExample.createCriteria().andLoginNameEqualTo(loginName);
        List<User> userList = userMapper.selectByExample(userExample);
        if(CollectionUtils.isEmpty(userList)){
            return null;
        }else {
            return userList.get(0);
        }
    }


    //根据登录名查询用户信息
    public LoginUserDto login(UserDto userDto){
        User userDb = selectByLoginName(userDto.getLoginName());
        //若用户不存在
        if(ObjectUtils.isEmpty(userDb)){
            LOG.info("用户不存在:{}",userDto.getLoginName());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        }else {
            //若密码匹对成功
            if(userDb.getPassword().equals(userDto.getPassword())){
                LoginUserDto loginUserDto = CopyUtil.copy(userDb, LoginUserDto.class);
                //为登录用户读取权限
                setAuth(loginUserDto);
                return loginUserDto;
            }else {
                LOG.info("密码错误,输入密码:{},数据库密码：{}",userDto.getPassword(),userDb.getPassword());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }

    //为登录用户获取权限
    private void setAuth(LoginUserDto loginUserDto){
        //得到资源列表
        List<ResourceDto> resourceDtoList=myUserMapper.findResources(loginUserDto.getId());
        loginUserDto.setResources(resourceDtoList);

        //整理所有权限的请求，用于接口拦截
        HashSet<String> requestSet= new HashSet<>();
        if(!CollectionUtils.isEmpty(resourceDtoList)){
            for (int i = 0,l=resourceDtoList.size(); i < l; i++) {
                ResourceDto resourceDto = resourceDtoList.get(i);
                String request = resourceDto.getRequest();
                //将数组字符串转为list
                List<String> requestList= JSON.parseArray(request,String.class);
                if(!CollectionUtils.isEmpty(requestList)){
                    //将list添加到set集合中
                    requestSet.addAll(requestList);
                }
            }
        }
        LOG.info("有权限的请求:{}",requestSet);
        loginUserDto.setRequests(requestSet);

    }

}
